﻿using Serilog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AME.Database
{
    public static class SqlClient
    {
        /// <summary>
        /// 单独创建SqlClinet(建议需要高性能，单独app，scheduler时使用)
        /// </summary>
        /// <param name="type"></param>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static SqlSugarClient CreateSqlClinet(DbType type,string connectionString)
        {
            //创建数据库对象 (用法和EF Dappper一样通过new保证线程安全)
            return new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = connectionString,
                DbType = type,
                IsAutoCloseConnection = true
            },
            db => {

                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    // 捕获SQL执行前的事件
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        // 使用Serilog记录SQL语句
                        Log.Information("Executing SQL: {Sql}", sql);
                        Log.Information("Parameters: {Parameters}", pars.ToDictionary(it => it.ParameterName, it => it.Value));
                    };
                    // 捕获SQL执行出错的事件
                    db.Aop.OnError = (ex) =>
                    {
                        Log.Error(ex, "SQL Execution Error");
                    };

                };
            });
        }
    }
}
